# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.paginator import Paginator 
from django.apps import apps
from django.forms.models import model_to_dict
from base.auth import MyTokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
from base.models import *
from base.auth import CustomJWTPermission
import logging
logger = logging.getLogger("custom")
class PermissionView(APIView):
    def post(self, request):
        model = apps.get_model('base', 'Permission')

        queryDict = request.data
        query = model.objects.filter(**queryDict)
        if not query.exists():
            return Response({'code': 500,'message': 'You do not have permission to access this resource'})
        dict_list = [model_to_dict(instance) for instance in query]
        return Response(dict_list)

#绝大部分查询可用的APIView    
class QueryView(APIView):
    
    def post(self, request):
        try:
            requestDict = request.data
        except:
            return Response({'code': 500,'msg': 'Invalid request json'})
        if not requestDict:
            return Response({'code': 500,'msg': 'Invalid request data'})
        if not requestDict.get('appName') or not requestDict.get('modelName'):
            return Response({'code': 500,'msg': 'Invalid request app or model name'})
        appName = requestDict.get('appName')
        modelName = requestDict.get('modelName')
        try:
            model = apps.get_model(appName, modelName)
        except LookupError:
            return Response({'msg': 'Invalid model'})
        queryDict = requestDict.get('query')
        excludeDict = requestDict.get('exclude')
        query = model.objects.all()
        size = requestDict.get('size',10)
        page = requestDict.get('page',1)
        
        if queryDict:
            query = query.filter(**queryDict)
        if excludeDict:
            query = query.exclude(**excludeDict)
        order_by = requestDict.get('order_by')
        if order_by:
            query = query.order_by(order_by)
        desc = requestDict.get('desc', False)
        if desc:
            query = query.order_by('-'+order_by)
        paginator = Paginator(query, size)
        page_obj = paginator.get_page(page)
        dict_list = [model_to_dict(instance) for instance in page_obj]
        return Response({'code': 200,'msg': 'success','data': dict_list,'size': size,'page': page ,'total': paginator.count})
    
class LoginView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

#获取菜单
class GetMenuView(APIView):
    def post(self, request):
        from .auth import get_user_menu
        user = request.user
        menu_list = get_user_menu(user)
        return Response({'code': 200,'msg': 'success','data': menu_list})
    
#获取所有权限树
class GetPermissionTreeView(APIView):
    def post(self, request):
        from .auth import get_permissions_tree
        permission_tree = get_permissions_tree()
        return Response({'code': 200,'msg': 'success','data': permission_tree})
    
#获取app信息
class AppDetailView(APIView):
    permission_classes = [CustomJWTPermission]
    def post(self, request):
        try:
            requestDict = request.data
        except:
            return Response({'code': 500,'msg': 'Invalid request json'})
        if not requestDict:
            return Response({'code': 500,'msg': 'Invalid request data'})
        if not requestDict.get('id'):
            return Response({'code': 500,'msg': 'Invalid request app id'})
        app = App.objects.filter(id=requestDict.get('id')).first()
        if not app:
            return Response({'code': 500,'msg': 'Invalid app'})
        dict_app = model_to_dict(app)
        permission_list = app.possess_permission.all()
        dict_app['permission_ids'] = [permission.id for permission in permission_list]
        return Response({'code': 200,'msg': 'success','data': dict_app})
    
class AppListView(APIView):
    permission_classes = [CustomJWTPermission]
    def post(self, request):
        try:
            requestDict = request.data
        except:
            return Response({'code': 500,'msg': 'Invalid request json'})
        if not requestDict:
            return Response({'code': 500,'msg': 'Invalid request data'})
        queryDict = requestDict.get('query')
        excludeDict = requestDict.get('exclude')
        query = App.objects.all()
        size = requestDict.get('size',20)
        page = requestDict.get('page',1)
        
        if queryDict:
            query = query.filter(**queryDict)
        if excludeDict:
            query = query.exclude(**excludeDict)
        order_by = requestDict.get('order_by')
        if order_by:
            query = query.order_by(order_by)
        desc = requestDict.get('desc', False)
        if desc:
            query = query.order_by('-'+order_by)
        paginator = Paginator(query, size)
        page_obj = paginator.get_page(page)
        
        dict_list = [model_to_dict(instance) for instance in page_obj]
        return Response({'code': 200,'msg': 'success','data': dict_list,'size': size,'page': page ,'total': paginator.count})
    
#修改或新增app信息
class SaveAppView(APIView):
    permission_classes = [CustomJWTPermission]
    def post(self, request):
        try:
            requestDict = request.data
        except:
            return Response({'code': 500,'msg': 'Invalid request json'})
        if not requestDict:
            return Response({'code': 500,'msg': 'Invalid request data'})
        app_dict = requestDict.get('app')
        if not app_dict:
            return Response({'code': 500,'msg': 'Invalid request app data'})
        if app_dict.get('id'):
            app = App.objects.filter(id=app_dict.get('id'))
            app.update(**app_dict)
            app = app.first()
        else:
            app = App(**app_dict)
            app.save()
        app.possess_permission.clear()    
        app.possess_permission.add(*requestDict.get('permission_ids',[]))
        app.save()
        return Response({'code': 200,'msg': 'success','data': model_to_dict(app)})
    
#删除app信息
class DeleteAppView(APIView):
    permission_classes = [CustomJWTPermission]
    def post(self, request):
        try:
            requestDict = request.data
        except:
            return Response({'code': 500,'msg': 'Invalid request json'})
        if not requestDict:
            return Response({'code': 500,'msg': 'Invalid request data'})
        if not requestDict.get('ids'):
            return Response({'code': 500,'msg': 'Invalid request ids'})
        App.objects.filter(id__in=requestDict.get('ids')).delete()
        return Response({'code': 200,'msg': 'success'})
        
#获取所有角色信息
class RoleListView(APIView):
    permission_classes = [CustomJWTPermission]
    def post(self, request):
        try:
            requestDict = request.data
        except:
            return Response({'code': 500,'msg': 'Invalid request json'})
        if not requestDict:
            return Response({'code': 500,'msg': 'Invalid request data'})
        queryDict = requestDict.get('query')
        excludeDict = requestDict.get('exclude')
        query = Role.objects.all()
        size = requestDict.get('size',20)
        page = requestDict.get('page',1)
        
        if queryDict:
            query = query.filter(**queryDict)
        if excludeDict:
            query = query.exclude(**excludeDict)
        order_by = requestDict.get('order_by')
        if order_by:
            query = query.order_by(order_by)
        desc = requestDict.get('desc', False)
        if desc:
            query = query.order_by('-'+order_by)
        paginator = Paginator(query, size)
        page_obj = paginator.get_page(page)
        
        dict_list = [model_to_dict(instance) for instance in page_obj]
        return Response({'code': 200,'msg': 'success','data': dict_list,'size': size,'page': page ,'total': paginator.count})
    
#获取角色信息
class RoleDetailView(APIView):
    permission_classes = [CustomJWTPermission]
    def post(self, request):
        try:
            requestDict = request.data
        except:
            return Response({'code': 500,'msg': 'Invalid request json'})
        if not requestDict:
            return Response({'code': 500,'msg': 'Invalid request data'})
        if not requestDict.get('id'):
            return Response({'code': 500,'msg': 'Invalid request role id'})
        role = Role.objects.filter(id=requestDict.get('id')).first()
        if not role:
            return Response({'code': 500,'msg': 'Invalid role'})
        dict_role = model_to_dict(role)
        permission_list = role.permissions.all()
        dict_role['permission_ids'] = [permission.id for permission in permission_list]
        return Response({'code': 200,'msg': 'success','data': dict_role})
    
#修改或新增角色信息
class SaveRoleView(APIView):
    permission_classes = [CustomJWTPermission]
    def post(self, request):
        try:
            requestDict = request.data
        except:
            return Response({'code': 500,'msg': 'Invalid request json'})
        if not requestDict:
            return Response({'code': 500,'msg': 'Invalid request data'})
        role_dict = requestDict.get('role')
        if not role_dict:
            return Response({'code': 500,'msg': 'Invalid request role data'})
        if role_dict.get('id'):
            role = Role.objects.filter(id=role_dict.get('id'))
            role.update(**role_dict)
            role = role.first()
        else:
            role = Role(**role_dict)
            role.save()
        role.permissions.clear()    
        role.permissions.add(*requestDict.get('permission_ids',[]))
        role.save()
        return Response({'code': 200,'msg': 'success','data': model_to_dict(role)})
    
#删除角色信息
class DeleteRoleView(APIView):
    permission_classes = [CustomJWTPermission]
    def post(self, request):
        try:
            requestDict = request.data
        except:
            return Response({'code': 500,'msg': 'Invalid request json'})
        if not requestDict:
            return Response({'code': 500,'msg': 'Invalid request data'})
        if not requestDict.get('ids'):
            return Response({'code': 500,'msg': 'Invalid request ids'})
        
        Role.objects.filter(id__in=requestDict.get('ids')).delete()
        return Response({'code': 200,'msg': 'success'})
    
#获取所有用户信息
class UserListView(APIView):
    permission_classes = [CustomJWTPermission]
    def post(self, request):
        try:
            requestDict = request.data
            print(requestDict)
        except:
            return Response({'code': 500,'msg': 'Invalid request json'})
        if not requestDict:
            return Response({'code': 500,'msg': 'Invalid request data'})
        queryDict = requestDict.get('query')
        excludeDict = requestDict.get('exclude')
        query = User.objects.all()
        size = requestDict.get('size',20)
        page = requestDict.get('page',1)
        if request.user.app_id:
            query = query.filter(app_id=request.user.app_id)
        if queryDict:
            query = query.filter(**queryDict)
        if excludeDict:
            query = query.exclude(**excludeDict)
        order_by = requestDict.get('order_by')
        if order_by:
            query = query.order_by(order_by)
        desc = requestDict.get('desc', False)
        if desc:
            query = query.order_by('-'+order_by)
        paginator = Paginator(query, size)
        page_obj = paginator.get_page(page)
        
        dict_list = [model_to_dict(instance) for instance in page_obj]
        return Response({'code': 200,'msg': 'success','data': dict_list,'size': size,'page': page ,'total': paginator.count})

#角色select,value为角色id,label为角色名称的列表
class RoleSelectView(APIView):
    def post(self, request):
        query = Role.objects.all()
        if request.user.app_id:
            query = query.filter(app_id=request.user.app_id)
        dict_list = [{'value': role.id, 'label': role.name} for role in query]
        return Response({'code': 200,'msg': 'success','data': dict_list})

#获取用户信息
class UserDetailView(APIView):
    permission_classes = [CustomJWTPermission]
    def post(self, request):
        try:
            requestDict = request.data
        except:
            return Response({'code': 500,'msg': 'Invalid request json'})
        if not requestDict:
            return Response({'code': 500,'msg': 'Invalid request data'})
        if not requestDict.get('id'):
            return Response({'code': 500,'msg': 'Invalid request user id'})
        user = User.objects.filter(id=requestDict.get('id')).first()
        if not user:
            return Response({'code': 500,'msg': 'Invalid user'})
        dict_user = model_to_dict(user)
        role_list = user.roles.values_list('id', flat=True).all()
        permission_list = user.permissions.values_list('id', flat=True).all()
        dict_user['permission_ids'] = list(permission_list)
        dict_user['role_ids'] = list(role_list)
        return Response({'code': 200,'msg': 'success','data': dict_user})
    
#修改或新增用户信息
class SaveUserView(APIView):
    permission_classes = [CustomJWTPermission]
    def post(self, request):
        try:
            requestDict = request.data
        except:
            return Response({'code': 500,'msg': 'Invalid request json'})
        if not requestDict:
            return Response({'code': 500,'msg': 'Invalid request data'})
        print(requestDict)
        role_ids = requestDict.get('roles',[])
        permission_ids = requestDict.get('permissions',[])
        print(permission_ids)
        requestDict.pop('roles')
        requestDict.pop('permissions')
        if requestDict.get('id'):
            user = User.objects.filter(id=requestDict.get('id'))
            if not user:
                return Response({'code': 500,'msg': 'Invalid user'})
            if not requestDict.get('password'):
                requestDict.pop('password')
            user.update(**requestDict)
            user = user.first()
        else:
            user = User(**requestDict)
        user.set_password(user.password)
        user.save()
        user.roles.clear()    
        user.roles.add(*role_ids)
        user.permissions.clear()
        user.permissions.add(*permission_ids)
        user.save()
        return Response({'code': 200,'msg': 'success','data': model_to_dict(user)})
    
#删除用户信息
class DeleteUserView(APIView):
    permission_classes = [CustomJWTPermission]
    def post(self, request):
        try:
            requestDict = request.data
        except:
            return Response({'code': 500,'msg': 'Invalid request json'})
        if not requestDict:
            return Response({'code': 500,'msg': 'Invalid request data'})
        if not requestDict.get('ids'):
            return Response({'code': 500,'msg': 'Invalid request ids'})
        User.objects.filter(id__in=requestDict.get('ids')).delete()
        return Response({'code': 200,'msg': 'success'})
    